package com.jk.vehicle.mini.util;

import com.google.common.collect.Lists;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.Collection;
import java.util.List;

/**
 * dozer对象拷贝工具类
 *
 * @author KangJian
 * @date 2018/07/23
 */
public class BeanMapperUtil {

	/**
	 * mapper映射
	 */
	private static DozerBeanMapper dozerBeanMapper;

	/**
	 * 日志
	 */
	private static Logger logger = LoggerFactory.getLogger(BeanMapperUtil.class);

	static {
		dozerBeanMapper = new DozerBeanMapper();
		String[] mappingFiles = {"bean-mappings.xml", "global-config.xml"};
		try {
			for (String path : mappingFiles) {
				InputStream inputStream = null;
				try {
					inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("dozer/" + path);
				} catch (Exception e) {
					logger.error("dozer文件不存在：" + path);
				}
				if (inputStream != null) {
					dozerBeanMapper.addMapping(inputStream);
					inputStream.close();
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}


	/**
	 * 基于Dozer转换对象的类型.
	 */
	public static <T> T map(Object source, Class<T> destinationClass) {
		return dozerBeanMapper.map(source, destinationClass);
	}


	/**
	 * 基于Dozer转换Collection中对象的类型.
	 */
	public static <T> List<T> mapList(Collection<?> sourceList, Class<T> destinationClass) {
		List<T> destinationList = Lists.newArrayList();
		for (Object sourceObject : sourceList) {
			T destinationObject = dozerBeanMapper.map(sourceObject, destinationClass);
			destinationList.add(destinationObject);
		}
		return destinationList;
	}


	/**
	 * 基于Dozer将对象A的值拷贝到对象B中.
	 */
	public static void convert(Object source, Object destinationObject) {
		dozerBeanMapper.map(source, destinationObject);
	}

}
